package com.example.springboot.service;

import com.example.springboot.dto.*;
import com.example.springboot.entity.ClothingRental;
import com.example.springboot.mapper.MerchantMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
public class MerchantService {
    @Autowired
    private MerchantMapper merchantMapper;

    private static final double EARTH_RADIUS = 6371.0; // 地球半径，单位：千米

    /**
     * 根据经纬度计算两点之间的距离
     */
    public double calculateDistance(double lat1, double lon1, double lat2, double lon2) {
        double latDistance = Math.toRadians(lat2 - lat1);
        double lonDistance = Math.toRadians(lon2 - lon1);

        double a = Math.sin(latDistance / 2) * Math.sin(latDistance / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                        Math.sin(lonDistance / 2) * Math.sin(lonDistance / 2);

        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        return EARTH_RADIUS * c;
    }

    /**
     * 获取按距离排序的商家列表
     */
    public List<MerchantDTO> getMerchantsByDistance(double latitude, double longitude) {
        List<MerchantDTO> merchants = merchantMapper.findMerchantFields();
        return merchants.stream()
                .peek(merchant -> {
                    double distance = calculateDistance(latitude, longitude, merchant.getLatitude(), merchant.getLongitude());
                    merchant.setDistance(distance);
                })
                .sorted(Comparator.comparingDouble(MerchantDTO::getDistance))
                .collect(Collectors.toList());
    }

    /**
     * 获取按距离排序的自助点列表
     */
    public List<SelfServicePointDTO> getSelfServicePointsByDistance(double latitude, double longitude) {
        List<SelfServicePointDTO> points = merchantMapper.findSelfServicePointFields();
        return points.stream()
                .peek(point -> {
                    double distance = calculateDistance(latitude, longitude, point.getLatitude(), point.getLongitude());
                    point.setDistance(distance);
                })
                .sorted(Comparator.comparingDouble(SelfServicePointDTO::getDistance))
                .collect(Collectors.toList());
    }
    /**
     * 根据商家ID获取商家详情
     */
    public MerchantDTO getMerchantById(int merchantId) {
        return merchantMapper.findMerchantById(merchantId);
    }
    /**
     * 根据自助点ID获取自助点详情
     */
    public SelfServicePointDTO getSelfServicePointById(int pointId) {
        return merchantMapper.findSelfServicePointById(pointId);
    }
    public String getServicesByMerchantId(int merchantId) {
        return merchantMapper.findServicesByMerchantId(merchantId);
    }
    /**
     * 根据商家ID获取订单列表
     */
    public List<MerchantOrderDTO> getOrdersByMerchantId(int merchantId) {
        return merchantMapper.findOrdersByMerchantId(merchantId);
    }

    public void updateMerchantAvatar(int merchantId, String avatarUrl) {
        merchantMapper.updateMerchantAvatar(merchantId, avatarUrl);
    }

    public void updateMerchantPoster(int merchantId, String posterUrl) {
        merchantMapper.updateMerchantPoster(merchantId, posterUrl);
    }
    public MerchantUsernameImageDTO getMerchantById(Integer merchantId) {
        return merchantMapper.selectMerchantById(merchantId);
    }
    public List<MerchantDTO> getAllMerchants() {
        return merchantMapper.selectAllMerchants();
    }

    public List<MerchantDTO> getMerchantsByAdminId(Integer adminId) {
        return merchantMapper.findMByAdminId(adminId);
    }


    /**
     * 新增商家
     */
    public Map<String, Object> addMerchant(MerchantManagementDTO merchantManagementDTO) {
        Map<String, Object> response = new HashMap<>();
        // 如果提供了明文密码，则加密存入 passwordHash
        if (merchantManagementDTO.getPassword() != null && !merchantManagementDTO.getPassword().isEmpty()) {
            String hashedPassword = BCrypt.hashpw(merchantManagementDTO.getPassword(), BCrypt.gensalt());
            merchantManagementDTO.setPasswordHash(hashedPassword);
        } else {
            throw new IllegalArgumentException("密码不能为空");
        }
        boolean success = merchantMapper.insertMerchantManagement(merchantManagementDTO) > 0;
        response.put("success", success);
        response.put("merchantId", merchantManagementDTO.getMerchantId());
        return response;
    }

    /**
     * 更新商家信息
     */
    public Map<String, Object> updateMerchant(int merchantId, MerchantManagementDTO merchantManagementDTO) {
        Map<String, Object> response = new HashMap<>();
        merchantManagementDTO.setMerchantId(merchantId);
        boolean success = merchantMapper.updateMerchantManagement(merchantManagementDTO) > 0;
        response.put("success", success);
        return response;
    }

    public Map<String, Object> deleteMerchant(int merchantId) {
        Map<String, Object> response = new HashMap<>();
        boolean success = merchantMapper.deleteMerchant(merchantId) > 0;
        response.put("success", success);
        return response;
    }

    public boolean updateMerchantName(int merchantId, String name) {
        return merchantMapper.updateMerchantName(merchantId, name) > 0;
    }

    public boolean updateMerchantServices(int merchantId, String services) {
        // 校验 services 是否符合数据库的 SET 类型
        if (!isValidServiceSet(services)) {
            throw new IllegalArgumentException("非法的 services 参数");
        }
        return merchantMapper.updateMerchantServices(merchantId, services) > 0;
    }

    private boolean isValidServiceSet(String services) {
        // 数据库定义的合法值
        Set<String> validServices = new HashSet<>(Arrays.asList("洗衣", "租赁", "保养", "修护"));
        // 拆分 services 并检查是否都在合法集合中
        return Arrays.stream(services.split(","))
                .allMatch(validServices::contains);
    }

    public List<SelfServicePointNameDTO> findByAdminId(Integer adminId) {
        return merchantMapper.findSByAdminId(adminId);
    }

    /**
     * 根据订单ID获取详细订单信息
     */
    public Map<String, Object> getOrderDetailById(int orderId) {
        // 获取订单基本信息
        Map<String, Object> orderDetail = merchantMapper.findOrderById(orderId);
        if (orderDetail == null) {
            return null;
        }

        // 如果是租赁订单，获取租赁商品详情
        String rentalIds = (String) orderDetail.get("rentalId");
        if (rentalIds != null && !rentalIds.isEmpty()) {
            String[] ids = rentalIds.split(",");
            List<ClothingRental> rentalItems = new ArrayList<>();
            for (String id : ids) {
                ClothingRental rental = merchantMapper.findClothingRentalById(Integer.parseInt(id.trim()));
                if (rental != null) {
                    rentalItems.add(rental);
                }
            }
            orderDetail.put("rentalItems", rentalItems);
        }

        // 获取收益信息
        Map<String, Object> earnings = merchantMapper.findEarningsByOrderId(orderId);
        if (earnings != null) {
            orderDetail.put("merchantEarnings", earnings.get("merchantEarnings"));
            orderDetail.put("platformEarnings", earnings.get("platformEarnings"));
        }

        // 获取评价信息
        Map<String, Object> review = merchantMapper.findReviewByOrderId(orderId);
        if (review != null) {
            orderDetail.put("rating", review.get("rating"));
            orderDetail.put("comment", review.get("comment"));
        }

        return orderDetail;
    }
}
